<template>
  <div class="app-container home">
    <el-row :gutter="20" style="margin-bottom: 12px;">
      <el-col :xs="24" :sm="24" :md="12">
        <div style="display:flex; align-items:center;">
          <h2 style="margin:0;">社团中心</h2>
          <el-tag type="info" style="margin-left:10px;">v{{ version }}</el-tag>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" style="text-align:right;">
        <el-button type="primary" size="small" @click="nav('/club/user/portal')">我的社团</el-button>
        <el-button size="small" @click="nav('/club/info')">社团信息</el-button>
        <el-button size="small" @click="nav('/club/recruitment')">社团招聘</el-button>
        <el-button size="small" @click="nav('/club/application')">报名申请</el-button>
        <el-button size="small" @click="nav('/club/profile')">兴趣性格</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="12" style="margin-bottom: 12px;">
      <el-col :xs="24" :sm="8" :md="8" :lg="8">
        <el-card>
          <div class="stat-title">社团总数</div>
          <div class="stat-value">{{ stats.clubTotal }}</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="8" :lg="8">
        <el-card>
          <div class="stat-title">已加入社团</div>
          <div class="stat-value">{{ stats.joinedTotal }}</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="8" :lg="8">
        <el-card>
          <div class="stat-title">开放招聘</div>
          <div class="stat-value">{{ stats.openRecruitTotal }}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="12" style="margin-bottom: 12px;">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>已加入社团活动提醒</span>
          </div>
          <div v-if="joinedClubs.length === 0" style="color:#909399;">暂未加入任何社团</div>
          <div v-else>
            <el-timeline>
              <el-timeline-item v-for="club in joinedClubs" :key="club.id" :timestamp="club.name">
                <div v-if="upcomingByClub[club.id] && upcomingByClub[club.id].length">
                  <ul class="list">
                    <li v-for="(act, idx) in upcomingByClub[club.id]" :key="idx">{{ act.title }}（{{ formatDate(act.activityTime) }}）</li>
                  </ul>
                </div>
                <div v-else style="color:#c0c4cc;">近期暂无活动</div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>热门社团推荐</span>
          </div>
          <el-row :gutter="12">
            <el-col :span="12" v-for="club in hotClubs" :key="club.id" style="margin-bottom: 12px;">
              <el-card shadow="hover">
                <div style="display:flex; justify-content:space-between; align-items:center;">
                  <div style="font-size: 15px; font-weight: 600;">{{ club.name }}</div>
                  <el-popover placement="left" width="360" trigger="hover" @show="loadClubActivitiesDetail(club)">
                    <div style="white-space: pre-line;">{{ club.introduction || '暂无介绍' }}</div>
                    <div style="margin-top:8px; font-weight:600;">往期活动</div>
                    <div v-if="club.activitiesLoading" style="padding:8px 0;">加载活动中...</div>
                    <ul v-else class="list">
                      <li v-for="(act, idx) in club.activities" :key="idx">{{ act.title }}（{{ formatDate(act.activityTime) }}）</li>
                      <li v-if="!club.activities || !club.activities.length">暂无活动</li>
                    </ul>
                    <div slot="reference" style="cursor:pointer; color:#409EFF;">悬浮查看详情</div>
                  </el-popover>
                </div>
                <div style="margin:8px 0; display:flex; flex-wrap:wrap; align-items:center;">
                  <el-tag v-for="(t, i) in club.tags" :key="'tag-'+i" type="info" style="margin:0 6px 6px 0;">{{ t }}</el-tag>
                  <el-button type="text" size="mini" @click="goApply(club)" style="margin-left:6px;">去报名</el-button>
                </div>
                <div style="display:flex; justify-content:space-between; align-items:center;">
                  <div>活跃度：{{ club.activityScore }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  
    <el-divider v-if="false" />
  </div>
</template>

<script>
import { listInfo } from '@/api/club/info'
import { listRelation } from '@/api/club/relation'
import { listActivity } from '@/api/club/activity'
import { listRecruitment } from '@/api/club/recruitment'
import { getUserProfile } from '@/api/system/user'

export default {
  name: 'Index',
  data() {
    return {
      version: '1.0.0',
      loading: false,
      userId: null,
      stats: { clubTotal: 0, joinedTotal: 0, openRecruitTotal: 0 },
      clubMap: {},
      joinedClubs: [],
      upcomingByClub: {},
      hotClubs: [],
      pollTimer: null
    }
  },
  created() {
    this.init()
    this.startPolling()
  },
  beforeDestroy() {
    this.stopPolling()
  },
  methods: {
    init() {
      this.loading = true
      getUserProfile().then(res => {
        const d = res.data || {}
        this.userId = d.userId || d.user?.userId || null
      }).catch(() => {
        this.userId = null
      }).finally(() => {
        this.loadData()
      })
    },
    loadData() {
      const infoQuery = { pageNum: 1, pageSize: 999 }
      listInfo(infoQuery).then(res => {
        const rows = res.rows || []
        this.stats.clubTotal = Number(res.total || rows.length || 0)
        const map = {}
        rows.forEach(r => { map[r.id] = r })
        this.clubMap = map
        const ranked = rows.slice().sort((a, b) => Number(b.activityScore || 0) - Number(a.activityScore || 0)).slice(0, 6)
        this.hotClubs = ranked.map(r => ({
          id: r.id,
          name: r.name,
          introduction: r.introduction,
          activityScore: r.activityScore,
          tags: (r.tags || '').split(',').map(s => s.trim()).filter(Boolean),
          activities: [],
          activitiesLoading: false
        }))
        if (this.userId) {
          this.loadRelations()
        } else {
          this.loading = false
        }
      }).catch(() => {
        this.stats.clubTotal = 0
        this.hotClubs = []
        if (this.userId) {
          this.loadRelations()
        } else {
          this.loading = false
        }
      })
      const recQuery = { pageNum: 1, pageSize: 999 }
      listRecruitment(recQuery).then(res => {
        const rows = res.rows || []
        const open = rows.filter(r => String(r.status) === '1').length
        this.stats.openRecruitTotal = open || rows.length || 0
      }).catch(() => {
        this.stats.openRecruitTotal = 0
      })
    },
    loadRelations() {
      const q = { pageNum: 1, pageSize: 999, userId: this.userId }
      listRelation(q).then(res => {
        const rows = res.rows || []
        const clubs = rows.map(r => this.clubMap[r.clubId]).filter(Boolean)
        this.joinedClubs = clubs
        this.stats.joinedTotal = clubs.length
        clubs.forEach(c => this.loadUpcoming(c))
        this.loading = false
      }).catch(() => {
        this.joinedClubs = []
        this.stats.joinedTotal = 0
        this.loading = false
      })
    },
    loadUpcoming(club) {
      if (!club || !club.id) return
      const q = { pageNum: 1, pageSize: 8, clubId: club.id, status: 0 }
      listActivity(q).then(res => {
        const rows = (res.rows || []).slice().sort((a, b) => new Date(a.activityTime).getTime() - new Date(b.activityTime).getTime())
        const now = new Date()
        const upcoming = rows.filter(a => {
          const t = new Date(a.activityTime)
          return t.getTime() >= now.getTime()
        }).slice(0, 3)
        this.$set(this.upcomingByClub, club.id, upcoming)
      }).catch(() => {
        this.$set(this.upcomingByClub, club.id, [])
      })
    },
    loadClubActivitiesDetail(club) {
      if (!club || club.activitiesLoading || (club.activities && club.activities.length)) return
      club.activitiesLoading = true
      const query = { pageNum: 1, pageSize: 5, clubId: club.id }
      listActivity(query).then(res => {
        const rows = res.rows || []
        club.activities = rows.map(a => ({ title: a.title, activityTime: a.activityTime }))
        club.activitiesLoading = false
      }).catch(() => {
        club.activitiesLoading = false
      })
    },
    formatDate(val) {
      if (!val) return ''
      const d = new Date(val)
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const da = String(d.getDate()).padStart(2, '0')
      return `${y}-${m}-${da}`
    },
    startPolling() {
      if (this.pollTimer) return
      this.pollTimer = setInterval(() => {
        if (this.joinedClubs && this.joinedClubs.length) {
          this.joinedClubs.forEach(c => this.loadUpcoming(c))
        } else if (this.userId) {
          this.loadRelations()
        }
      }, 60000)
      if (typeof document !== 'undefined') {
        document.addEventListener('visibilitychange', this.onVisibilityChange)
      }
    },
    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
        this.pollTimer = null
      }
      if (typeof document !== 'undefined') {
        document.removeEventListener('visibilitychange', this.onVisibilityChange)
      }
    },
    onVisibilityChange() {
      if (typeof document !== 'undefined' && !document.hidden) {
        if (this.userId) {
          this.loadRelations()
        } else {
          this.init()
        }
      }
    },
    nav(path) {
      const fixed = typeof path === 'string' && !/^\//.test(path) ? '/' + path : path
      if (this.$router) {
        this.$router.push({ path: fixed }).catch(() => {})
      } else {
        window.open(fixed, '_self')
      }
    },
    goTarget(href) {
      window.open(href, '_blank')
    },
    goApply(club) {
      const url = `http://localhost/c/application?clubId=${club.id}`
      window.open(url, '_self')
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  .stat-title { font-size: 13px; color: #909399; }
  .stat-value { font-size: 24px; font-weight: 600; margin-top: 6px; }
  .list { padding-left: 16px; margin: 6px 0; }
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
</style>

